<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>20-自定义事件内容分发</title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
	<h3></h3>
	<hr>
	
	<div id="app">

		<books>
			<book-title slot="book-title" :title="title"></book-title>

			<hr>
			<!-- 
			<book-add slot="book-add" :new_book="new_book" 
				@cre_one="add(new_book)"></book-add> -->

			<book-list slot="book-list" v-for="(book,index) in books"
				@del_one="remove(index)" :book="book" :index="index" :key="index"></book-list>

		</books>


	</div>

	<script>

		Vue.component("books", {
			// <slot name ="book-add"></slot>\
			template: '	<div>\
							\
							<slot name="book-title"></slot>\
							<ul>\
								<slot name="book-list"></slot>\
							</ul>\
						</div>'
		});

		Vue.component("book-title", {
			props: ["title"],
			template: '<p>{{title}}</p>'
		});

	
		/* Vue.component("book-add", {
			props: ["new_book"],
			template: '<input type="text" v-model="new_book" placeholder="输入后回车添加" @keyup.enter="cre(new_book)"/>', // @keyup.enter=cre(newBook)
			methods:{
				cre:function(new_book){
					this.$emit('cre_one',new_book);
					// alert("添加书籍" + newBook)
				}
			}
		}); */


		Vue.component("book-list", {
			props: ["book", "index"],
			template: '<li> {{index}} -> {{book}}&emsp;<button @click="del(index)" >删除</button></li>',
			methods: {
				del: function (index) {
					// 自定义事件分发
					this.$emit("del_one",index)
				}
			}
		});


		var vue = new Vue({
			el: "#app",
			data: {
				title: "在读",
				books: ["《一个叫欧维的男人决定去死》", "《大道朝天》", "《将夜》", "《剑来》"],
				new_book:""
			},
			methods: {
				remove: function (index) {
					console.log("删除了" + this.books[index]);
					this.books.splice(index, 1);
				},
				add:function(bookName){
					if(bookName.trim() != "") {
						bookName = "《" + bookName + "》";
						this.books.push(bookName);
						console.log("添加了" + bookName);
						this.new_book="";
					}
				}
			}
		});
	</script>

</body>

</html>